package com.cungmua.app.activity;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.cungmua.app.R;
import com.cungmua.app.base.BaseDrawerActivitys;
import com.cungmua.app.handler.RegisterHandler;
import com.cungmua.app.model.Cart;
import com.cungmua.app.model.User;
import com.cungmua.app.model.request.LoginRequest;
import com.cungmua.app.model.request.RegisterRequest;
import com.cungmua.app.model.response.RegisterResponse;
import com.cungmua.app.task.RegisterTask;
import com.cungmua.app.utils.AppUtils;

import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * Created by kelvin.nguyen on 7/1/14.
 */
public class RegisterActivity extends BaseDrawerActivitys implements View.OnClickListener, RegisterHandler {

    private EditText txtName;
    private EditText txtPhone;
    private EditText txtDateOfBirth;
    private EditText txtEmail;
    private EditText txtPassword;
    private EditText txtPasswordConfirmation;
    private CheckBox chkTOS;
    private Button btnRegister;
    private int birthYear;
    private int birthMonth;
    private int birthDay;
    private RegisterRequest registerRequest;
    private RadioButton rdMale;
    private RadioButton rdFemale;
    private TextView txtTermOfService;

    private ImageView icon_home;
    private Button icon_cart;
    private LinearLayout btnCart;


    @Override
    public int getLayoutResource() {
        return R.layout.activity_register;
    }

    @Override
    public void updateView() {

    }

    @Override
    public void loadControls(Bundle savedInstanceState) {
        birthYear = 1990;
        birthMonth = 0;
        birthDay = 1;
        txtTermOfService = (TextView) findViewById(R.id.txtTermOfService);
        txtName = (EditText) findViewById(R.id.txtName);
        txtPhone = (EditText) findViewById(R.id.txtPhone);
        txtDateOfBirth = (EditText) findViewById(R.id.txtDateOfBirth);
        txtEmail = (EditText) findViewById(R.id.txtEmail);
        txtPassword = (EditText) findViewById(R.id.txtPassword);
        txtPasswordConfirmation = (EditText) findViewById(R.id.txtPasswordConfirmation);
        chkTOS = (CheckBox) findViewById(R.id.chkTOS);
        btnRegister = (Button) findViewById(R.id.btnRegister);
        rdMale = (RadioButton) findViewById(R.id.rdMale);
        rdFemale = (RadioButton) findViewById(R.id.rdFemale);

        txtTermOfService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.cungmua.com/quy-che-cung-mua-khuyen-mai-gia-re.html"));
                startActivity(intent);
            }
        });

//        chkTOS.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
//                btnRegister.setEnabled(b);
//            }
//        });

        txtDateOfBirth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DatePickerDialog dialog = new DatePickerDialog(RegisterActivity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker datePicker, int year, int month, int day) {
                        birthYear = year;
                        birthMonth = month;
                        birthDay = day;

                        SimpleDateFormat format = AppUtils.getShowDateFormatter();
                        Calendar cal = Calendar.getInstance();
                        cal.set(year, month, day);

                        txtDateOfBirth.setText(format.format(cal.getTime()));
                    }
                }, birthYear, birthMonth, birthDay);
                dialog.getDatePicker().setMaxDate(System.currentTimeMillis());
                dialog.show();
            }
        });
        txtDateOfBirth.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean focused) {
                if (focused) {
                    DatePickerDialog dialog = new DatePickerDialog(RegisterActivity.this, new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker datePicker, int year, int month, int day) {
                            birthYear = year;
                            birthMonth = month;
                            birthDay = day;

                            SimpleDateFormat format = AppUtils.getShowDateFormatter();
                            Calendar cal = Calendar.getInstance();
                            cal.set(year, month, day);

                            txtDateOfBirth.setText(format.format(cal.getTime()));
                        }
                    }, birthYear, birthMonth, birthDay);
                    dialog.getDatePicker().setMaxDate(System.currentTimeMillis());
                    dialog.show();
                }
            }
        });
        btnRegister.setOnClickListener(this);

        icon_home=(ImageView)findViewById(R.id.icon_home);
        icon_cart=(Button)findViewById(R.id.icon_cart);
        btnCart=(LinearLayout)findViewById(R.id.btnCart);


        Cart currentCart=getCurrentCart();
        icon_cart.setText(currentCart.getTotalQuantity()+"");

        icon_home.setOnClickListener(new ImageView.OnClickListener() {
            @Override
            public void onClick(View v) {
                showMenu();
            }
        });

        btnCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToYourCart();
            }
        });

    }

    @Override
    public void onClick(View view) {
        if (!validateFields())
            return;
        User user = new User();
        user.setEmail(txtEmail.getText().toString());
        user.setName(txtName.getText().toString());
        user.setMobile(txtPhone.getText().toString());
        user.setGender(rdMale.isChecked() ? 0 : 1);
        Calendar cal = Calendar.getInstance();
        cal.set(birthYear, birthMonth, birthDay);

        user.setDateOfBirth(cal.getTime());

        registerRequest = new RegisterRequest(getDeviceId(), getToken());
        registerRequest.setUser(user);
        registerRequest.setPassword(AppUtils.MD5(txtPassword.getText().toString()));
        RegisterTask task = new RegisterTask(this, this);
        task.execute(registerRequest);
    }

    public void alert(String alert) {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setMessage(alert)
                .setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                })
                .show();
    }


    private boolean validateFields() {
        if (txtName.getText().toString().isEmpty()) {
            alert(getString(R.string.must_have_name));
            return false;
        }
        if (txtPhone.getText().toString().isEmpty()) {
            alert(getString(R.string.must_have_phone));
            return false;
        }
        if (txtDateOfBirth.getText().toString().isEmpty()) {
            alert(getString(R.string.must_have_dob));
            return false;
        }
        if (txtEmail.getText().toString().isEmpty()) {
            alert(getString(R.string.must_have_email));
            return false;
        }
        if (!AppUtils.isValidEmail(txtEmail.getText())) {
            alert(getString(R.string.invalid_email));
            return false;
        }
        if (txtPassword.getText().toString().isEmpty()) {
            alert(getString(R.string.must_have_password));
            return false;
        }
        if (txtPassword.getText().length() < 6) {
            alert(getString(R.string.password_min_length, 6));
            return false;
        }
        if (!txtPassword.getText().toString().equals(txtPasswordConfirmation.getText().toString())) {
            alert(getString(R.string.wrong_password_confirmation));
            return false;
        }
        if (!rdMale.isChecked() && !rdFemale.isChecked()) {
            alert(getString(R.string.must_choose_gender));
            return false;
        }
        if (!chkTOS.isChecked()) {
            alert(getString(R.string.condition));
            return false;
        }
        if (txtPhone.getText().toString().length() < 10 || txtPhone.getText().toString().length() > 11 ||
                !txtPhone.getText().toString().startsWith("0")) {
            alert("Số điện thoại nhập không đúng. Vui lòng nhập lại.");
            return false;
        } else if (txtPhone.getText().toString().startsWith("02") ||
                txtPhone.getText().toString().startsWith("03") || txtPhone.getText().toString().startsWith("04") ||
                txtPhone.getText().toString().startsWith("05") || txtPhone.getText().toString().startsWith("06") ||
                txtPhone.getText().toString().startsWith("07") || txtPhone.getText().toString().startsWith("08")) {
            alert("Số điện thoại nhập không đúng. Vui lòng nhập lại.");
            return false;
        } else if (txtPhone.getText().toString().startsWith("09") && txtPhone.getText().toString().length() != 10) {
            alert("Số điện thoại nhập không đúng. Vui lòng nhập lại.");
            return false;
        } else if (txtPhone.getText().toString().startsWith("01") && txtPhone.getText().toString().length() != 11) {
            alert("Số điện thoại nhập không đúng. Vui lòng nhập lại.");
            return false;
        } if (!txtPhone.getText().toString().matches("[0-9]+")) {
            alert("Số điện thoại nhập không đúng. Vui lòng nhập lại.");
            return false;
        }
        return true;
    }

    @Override
    public void onRegistered(RegisterResponse data) {
        if (data.getCode() == 0) {
            User user = data.getData();
            LoginRequest request = new LoginRequest(getDeviceId(), getToken());

            request.setEmail(user.getEmail());
            request.setPassword(registerRequest.getPassword());

            setLastLoginRequest(request);
            setCurrentUser(user);

            Toast.makeText(this, R.string.registered, Toast.LENGTH_LONG).show();

            setResult(RESULT_OK);
            finish();
        } else {
            alert(data.getMessage());
        }
    }
}

